package cn.bonoon.services.plugins;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.plugins.PlaceService;
import cn.bonoon.entities.plugins.PlaceEntity;
import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.support.services.AbstractTreeService;
import cn.bonoon.kernel.util.StringHelper;

@Service
@Transactional(readOnly = true)
public class PlaceServiceImpl extends AbstractTreeService<PlaceEntity>
		implements PlaceService {

	@Override
	public List<PlaceEntity> children(long id) {
		return __list(
				domainClass,
				"select x from PlaceEntity x where x.deleted=false and x.parent.id=?",
				id);
	}

	@Override
	public List<PlaceEntity> byLevel(int level) {
		return __list(
				domainClass,
				"select x from PlaceEntity x where x.deleted=false and x.level=?",
				level);
	}

	@Override
	public int placeLevel(Long id) {
		return __single(Integer.class,
				"select x.level from PlaceEntity x where x.id=?", id)
				.intValue();
	}

	private void __parent(PlaceEntity entity) {
		PlaceEntity parent = entity.getParent();
		if (parent != null) {
			__parent2(parent);
			if (StringHelper.isEmpty(entity.getCode())) {
				entity.setCode(parent.getCode());
			}
		}
	}

	private void __parent2(PlaceEntity entity) {
		PlaceEntity parent = entity.getParent();
		if (parent != null) {
			__parent2(parent);
			entity.setFullName(parent.getFullName() + entity.getName());
			entity.setXpath(parent.getXpath() + entity.getId() + "/");
		} else {
			entity.setFullName(entity.getName());
			entity.setXpath(entity.getId() + "/");
		}
		entity.setSize(entity.getChildren().size());
	}

	@Override
	protected PlaceEntity __save(OperateEvent event, PlaceEntity entity) {
		__parent(entity);
		return super.__save(event, entity);
	}

	@Override
	protected PlaceEntity __update(OperateEvent event, PlaceEntity entity) {
		__parent(entity);
		entity.setSize(entity.getChildren().size());
		return super.__update(event, entity);
	}

	@Override
	public List<Object[]> getPlaceId_name(Set<Long> ids) {
		String hql = "select id,name from PlaceEntity where deleted=false and id in (";
		int i = 0;
		for (long id : ids) {

			if (i != ids.size() - 1) {
				hql += id + ",";
			} else {
				hql += id + ")";
			}
			i++;
		}

		return __list(Object[].class, hql);
	}
}
